﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlockOS.Server.FileIO
{
    public interface IFileTask
    {
        string FileName { get; }
        void Run(Stream stream);
        void Done();
    }

    public class ReadTask<T> : IFileTask
    {
        public string FileName { get; private set; }

        private readonly Func<Stream, T> readFunc;
        private T output;
        private readonly Action<T> doneCallback;

        public ReadTask(string fileName, Func<Stream, T> read, Action<T> doneCallback)
        {
            FileName = fileName;
            readFunc = read;
            this.doneCallback = doneCallback;
        }

        public void Run(Stream stream)
        {
            output = readFunc(stream);
        }

        public void Done()
        {
            doneCallback(output);
        }
    }

    public class WriteTask : IFileTask
    {
        public string FileName { get; private set; }

        private readonly Action<Stream> writeFunc;
        private readonly Action doneCallback;

        public WriteTask(string fileName, Action<Stream> write, Action doneCallback)
        {
            FileName = fileName;
            writeFunc = write;
            this.doneCallback = doneCallback;
        }

        public void Run(Stream stream)
        {
            writeFunc(stream);
        }

        public void Done()
        {
            doneCallback?.Invoke();
        }
    }
}
